#include "gtrans.h"
#include "ui_gtrans.h"


void GTrans::on_buttonParamConnexionModifier_clicked()
{
    QSettings s;
    s.setValue("connexion/host",ui->lineParamConnexionHost->text());

}

void GTrans::on_buttonParamConnexionAnnuler_clicked()
{
    QSettings s;
    ui->lineParamConnexionHost->setText(s.value("connexion/host","").toString());
}

void GTrans::on_buttonParamBanqueAjouter_clicked()
{
    //Ajout
    bool ok = false;
    QString n = QInputDialog::getText(this,"Ajouter banque","Quel banque voulez vous ajouter ?",QLineEdit::Normal,"",&ok);
    ui->listParamBanque->addItem(n);

    //Enregistrement
    QStringList banques;
    for(int i = 0; i< ui->listParamBanque->count(); i++){
        banques << ui->listParamBanque->item(i)->text();
    }

    QSettings s;
    s.setValue("trans/banques",banques);
}

void GTrans::on_buttonParamBanquesRetirer_clicked()
{
    //Retrait
    ui->listParamBanque->removeItemWidget(ui->listParamBanque->currentItem());

    //Enregistrement
    QStringList banques;
    for(int i = 0; i< ui->listParamBanque->count(); i++){
        banques << ui->listParamBanque->item(i)->text();
    }

    QSettings s;
    s.setValue("trans/banques",banques);
}

void GTrans::on_spinParamCompteFams_valueChanged(int arg1)
{
    if(arg1 != 0){

        //Si la valeur devient non nulle, on recherche les proms
        QSqlQueryModel *m = new QSqlQueryModel(this);
        QSqlQuery q(db);
        q.prepare("SELECT proms FROM v_users WHERE fams = :f");
        q.bindValue(":f",arg1);
        q.exec();
        m->setQuery(q);
        ui->comboParamCompteProms->setModel(m);

    } else {

        //Si elle est nulle on reinitialise les proms (en supprimant le modele)
        QAbstractItemModel *m = ui->comboParamCompteProms->model();
        delete m;
    }
}

void GTrans::on_buttonParamCompteModifier_clicked()
{
    if(ui->spinParamCompteFams->value() != 0){
        QSqlQuery q(db);
        q.prepare("SELECT get_compte(:f,get_proms(:p))");
        q.bindValue(":f",ui->spinParamCompteFams->value());
        q.bindValue(":p",ui->comboParamCompteProms->currentText());
        q.exec();
        q.first();
        if(q.value(0).toInt() > 0){
            QSettings s;
            s.setValue("trans/compte",q.value(0).toInt());
        }
    }

}

void GTrans::on_buttonParamCompteAnnuler_clicked()
{
    QSettings s;
    if(s.value("trans/compte",0).toInt() != 0){
        QSqlQuery q(db);
        q.prepare("SELECT fams, proms FROM v_users WHERE id = :i");
        q.bindValue(":i",s.value("trans/compte",0).toInt());
        q.exec();
        q.first();
        ui->spinParamCompteFams->setValue(q.value(0).toInt());
        ui->comboParamCompteProms->setCurrentText(q.value(1).toString());
    }
}
